﻿
using AmazonMODEL;
using MarketplaceWebServiceOrders.Model;
using MODEL;
using Newtonsoft.Json;
using SysHelper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SysController
{
    /*  
            SELECT a.AccountInfoID,a.AccountInfoName,a.RunServices,
            m.MerchantCode AS MerchantID,m.AppName,m.AppVersion ,m.AccessKey,m.AccessSecret,
            mp.MarketplaceCode,
            u.MarketplaceWebServiceURL,u.MarketplaceWebServiceOrdersURL FROM con.AccountInfo a
            Left join mws.Merchant m with(nolock) on m.MerchantID=a.MerchantID
            left join mws.Marketplaces mp with(nolock) on mp.MarketplacesID=m.MarketplacesID
            left join mws.MarketplaceServiceURL u with(nolock) on u.MarketplacesID=mp.MarketplacesID 
            WHERE a.IsDel=0 
        */
    public static partial class OrdersController
    {
        #region 2015-11-07 下载订单 + static List<OrderModel> ListOrders(AppKey appkey)
        /// <summary>
        /// 2015-11-07 下载订单
        /// </summary>
        /// <param name="appkey"></param>
        /// <returns></returns>
        public static List<OrderModel> ListOrders(AppKey appkey)
        {
            bool IsAgain = true;
        Again:
            ListOrdersRequest request = new ListOrdersRequest()
            {
                MarketplaceId = new MarketplaceIdList() { Id = new List<string>() { appkey.MarketplaceCode } },
                SellerId = appkey.MerchantCode,
                OrderStatus = new OrderStatusList() { Status = new List<OrderStatusEnum>() { OrderStatusEnum.Unshipped, OrderStatusEnum.PartiallyShipped } },
                LastUpdatedAfter = DateTime.Now.AddDays(-3)
            };
            try
            {
                ListOrdersResponse response = HelperController.RegisterOrdersService(appkey).ListOrders(request);
                if (response.IsSetListOrdersResult())
                {
                    ListOrdersResult result = response.ListOrdersResult;
                    string str = JsonConvert.SerializeObject(result);
                    List<OrderModel> list = new List<OrderModel>();
                    foreach (var item in result.Orders.Order)
                    {
                        OrderModel model = new OrderModel()
                        {
                            #region Order
                            Order = new AmazonOrder()
                            {
                                AccountInfoId = appkey.AccountInfoID,
                                SiteId=appkey.SiteID,
                                AmazonOrderId = item.AmazonOrderId,
                                BuyerEmail = item.BuyerEmail,
                                BuyerName = item.BuyerName,
                                CbaDisplayableShippingLabel = item.CbaDisplayableShippingLabel,
                                CreateTime = DateTime.Now,
                                CreateUser = "ListOrders",
                                EarliestShipDate = item.EarliestShipDate,
                                MarketplaceId = item.MarketplaceId,
                                NumberOfItemsShipped = item.NumberOfItemsShipped,
                                NumberOfItemsUnshipped = item.NumberOfItemsUnshipped,
                                LastUpdateDate = item.LastUpdateDate,
                                LatestShipDate = item.LatestShipDate,
                                FulfillmentChannel = item.FulfillmentChannel.ToString(),
                                IsDel = false,
                                PaymentMethod = item.PaymentMethod.ToString(),
                                OrderChannel = item.OrderChannel,
                                OrderStatus = item.OrderStatus.ToString(),
                                OrderType = item.OrderType,
                                PurchaseDate = item.PurchaseDate,
                                SalesChannel = item.SalesChannel,
                                SellerOrderId = item.SellerOrderId,
                                ShipmentServiceLevelCategory = item.ShipmentServiceLevelCategory,
                                ShippedByAmazonTFM = item.ShippedByAmazonTFM,
                                ShipServiceLevel = item.ShipServiceLevel,
                                TFMShipmentStatus = item.TFMShipmentStatus,
                                IsDetails = false
                            },
                            #endregion
                            #region ShippingAddress
                            ShippingAddress = new AmazonOrdersShippingAddress()
                                               {
                                                   AccountInfoId = appkey.AccountInfoID,
                                                   SiteId = appkey.SiteID,
                                                   AddressLine1 = item.ShippingAddress.AddressLine1,
                                                   AddressLine2 = item.ShippingAddress.AddressLine2,
                                                   AddressLine3 = item.ShippingAddress.AddressLine3,
                                                   AmazonOrderId = item.AmazonOrderId,
                                                   City = item.ShippingAddress.City,
                                                   CountryCode = item.ShippingAddress.CountryCode,
                                                   County = item.ShippingAddress.County,
                                                   CreateTime = DateTime.Now,
                                                   CreateUser = "ListOrders",
                                                   District = item.ShippingAddress.District,
                                                   IsDel = false,
                                                   IsShip = false,
                                                   Name = item.ShippingAddress.Name,
                                                   Phone = item.ShippingAddress.Phone,
                                                   PostalCode = item.ShippingAddress.PostalCode,
                                                   StateOrRegion = item.ShippingAddress.StateOrRegion
                                               },
                            #endregion
                            #region Total
                            Total = new AmazonOrdersTotal()
                                              {
                                                  AccountInfoId = appkey.AccountInfoID,
                                                  SiteId = appkey.SiteID,
                                                  AmazonOrderId = item.AmazonOrderId,
                                                  CurrencyCode = item.OrderTotal.CurrencyCode,
                                                  Amount = Convert.ToDecimal(item.OrderTotal.Amount),
                                                  CreateTime = DateTime.Now,
                                                  CreateUser = "ListOrders",
                                                  IsDel = false
                                              }
                            #endregion
                        };
                        list.Add(model);
                    }
                    return list;
                }
                return null;
            }
            catch (Exception)
            {
                if (IsAgain)
                {
                    IsAgain = false;
                    goto Again;
                }
                return null;
            }
        }
        #endregion

        #region  2015-11-08 下载订单明细 + static List<AmazonOrdersDetail> ListOrderItems(AppKey appkey, string AmazonOrderId)
        /// <summary>
        /// 2015-11-08 下载订单明细
        /// </summary>
        /// <param name="appkey"></param>
        /// <param name="AmazonOrderId"></param>
        /// <returns></returns>
        public static List<AmazonOrdersDetail> ListOrderItems(AppKey appkey, string AmazonOrderId)
        {
            bool IsAgain = true;
        Again:
            ListOrderItemsRequest request = new ListOrderItemsRequest()
            {
                AmazonOrderId = AmazonOrderId,
                SellerId = appkey.MerchantCode
            };
            try
            {
                ListOrderItemsResponse response = HelperController.RegisterOrdersService(appkey).ListOrderItems(request);
                if (response.IsSetListOrderItemsResult())
                {
                    ListOrderItemsResult result = response.ListOrderItemsResult;
                    string str = JsonConvert.SerializeObject(result);
                    List<OrderItem> list = result.OrderItems.OrderItem;
                    List<AmazonOrdersDetail> detailList = new List<AmazonOrdersDetail>();
                    foreach (var item in list)
                    {
                        AmazonOrdersDetail detail = new AmazonOrdersDetail()
                        {
                            AccountInfoId = appkey.AccountInfoID,
                            AmazonOrderId = AmazonOrderId,
                            SiteId = appkey.SiteID,
                            ASIN = item.ASIN,
                            ConditionId = item.ConditionId ?? "",
                            ConditionNote = item.ConditionNote ?? "",
                            ConditionSubtypeId = item.ConditionSubtypeId ?? "",
                            CreateTime = DateTime.Now,
                            CreateUser = "ListOrderItems",
                            GiftMessageText = item.GiftMessageText ?? "",
                            GiftWrapLevel = item.GiftWrapLevel ?? "",
                            IsDel = false,
                            OrderItemId = item.OrderItemId,
                            QuantityOrdered = item.QuantityOrdered,
                            QuantityShipped = item.QuantityShipped,
                            ScheduledDeliveryEndDate = item.ScheduledDeliveryEndDate ?? "",
                            ScheduledDeliveryStartDate = item.ScheduledDeliveryStartDate ?? "",
                            SellerSKU = item.SellerSKU,
                            Title = item.Title
                        };
                        if (item.IsSetPromotionIds())
                        {
                            PromotionIdList ls = item.PromotionIds;
                            if (ls.IsSetPromotionId())
                            {
                                detail.PromotionIds = string.Join(",", item.PromotionIds.PromotionId);
                            }
                        }
                        if (item.IsSetCODFeeDiscount())
                        {
                            detail.CODFeeDiscountAmount = Convert.ToDecimal(item.CODFeeDiscount.Amount);
                            detail.CODFeeDiscountCurrencyCode = item.CODFeeDiscount.CurrencyCode;
                        }
                        if (item.IsSetCODFee())
                        {
                            detail.CODFeeAmount = Convert.ToDecimal(item.CODFee.Amount);
                            detail.CODFeeCurrencyCode = item.CODFee.CurrencyCode;
                        }
                        if (item.IsSetGiftWrapTax())
                        {
                            detail.GiftWrapTaxAmount = Convert.ToDecimal(item.GiftWrapTax.Amount);
                            detail.GiftWrapTaxCurrencyCode = item.GiftWrapTax.CurrencyCode;
                        }
                        if (item.IsSetGiftWrapPrice())
                        {
                            detail.GiftWrapPriceAmount = Convert.ToDecimal(item.GiftWrapPrice.Amount);
                            detail.GiftWrapPriceCurrencyCode = item.GiftWrapPrice.CurrencyCode;
                        }
                        if (item.IsSetItemTax())
                        {
                            detail.ItemTaxAmount = Convert.ToDecimal(item.ItemTax.Amount);
                            detail.ItemTaxCurrencyCode = item.ItemTax.CurrencyCode;
                        }
                        if (item.IsSetItemPrice())
                        {
                            detail.ItemPriceAmount = Convert.ToDecimal(item.ItemPrice.Amount);
                            detail.ItemPriceCurrencyCode = item.ItemPrice.CurrencyCode;
                        }

                        if (item.IsSetPromotionDiscount())
                        {
                            detail.PromotionDiscountAmount = Convert.ToDecimal(item.PromotionDiscount.Amount);
                            detail.PromotionDiscountCurrencyCode = item.PromotionDiscount.CurrencyCode;
                        }
                        if (item.IsSetShippingTax())
                        {
                            detail.ShippingTaxAmount = Convert.ToDecimal(item.ShippingTax.Amount);
                            detail.ShippingTaxCurrencyCode = item.ShippingTax.CurrencyCode;
                        }

                        if (item.IsSetShippingPrice())
                        {
                            detail.ShippingPriceAmount = Convert.ToDecimal(item.ShippingPrice.Amount);
                            detail.ShippingPriceCurrencyCode = item.ShippingPrice.CurrencyCode;
                        }
                        if (item.IsSetInvoiceData())
                        {
                            detail.BuyerSelectedInvoiceCategory = item.InvoiceData.BuyerSelectedInvoiceCategory;
                            detail.InvoiceInformation = item.InvoiceData.InvoiceInformation;
                            detail.InvoiceRequirement = item.InvoiceData.InvoiceRequirement;
                            detail.InvoiceTitle = item.InvoiceData.InvoiceTitle;
                        }
                        if (item.IsSetShippingDiscount())
                        {
                            detail.ShippingDiscountAmount = Convert.ToDecimal(item.ShippingDiscount.Amount);
                            detail.ShippingDiscountCurrencyCode = item.ShippingDiscount.CurrencyCode;
                        }
                        detailList.Add(detail);
                    }
                    return detailList;
                }
                return null;
            }
            catch (Exception)
            {
                if (IsAgain)
                {
                    IsAgain = false;
                    goto Again;
                }
                return null;
            }
        }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="appkey"></param>
        /// <param name="AmazonOrderIdList"></param>
        public static void GetOrder(AppKey appkey, List<string> AmazonOrderIdList)
        {
            GetOrderRequest request = new GetOrderRequest()
            {
                AmazonOrderId = new OrderIdList() { Id = new List<string>() },
                SellerId = appkey.MerchantCode
            };
            request.AmazonOrderId.Id = AmazonOrderIdList;

            try
            {
                GetOrderResponse response = HelperController.RegisterOrdersService(appkey).GetOrder(request);
                if (response.IsSetGetOrderResult())
                {
                    OrderList list = response.GetOrderResult.Orders;
                }
            }
            catch (Exception)
            {

                throw;
            }



        }

       
    }

    public static partial class OrdersController
    {
        public static FeedsInfo OrderFulfillment(AppKey appkey)
        {
            List<AmazonOrderFulfillment> list = SystemController.GetAmazonOrderFulfillment(appkey);
            if (list==null||list.Count<1)
            {
                return null;
            }
            List<AmazonOrderFulfillmentItem> itemList = SystemController.GetAmazonOrderFulfillmentItem(list);
            List<string> orderList = new List<string>();
            foreach (var item in list)
            {
                List<AmazonOrderFulfillmentItem> itList = itemList.Where(s => s.AmazonOrderID == item.AmazonOrderID && s.AccountInfoId == item.AccountInfoId).ToList();
                List<OrderFulfillmentItem> orderItemList = new List<OrderFulfillmentItem>();
                foreach (var it in itList)
                {
                    OrderFulfillmentItem model = new OrderFulfillmentItem()
                    {
                        Item = it.AmazonOrderItemID,
                        ItemElementName = ItemChoiceType1.AmazonOrderItemCode,
                        Quantity = it.ShipedQty.ToString() ?? it.OrderQty.ToString()
                    };
                    orderItemList.Add(model);
                }
                OrderFulfillment Model = new OrderFulfillment()
                {
                    Item = item.AmazonOrderID,
                    ItemElementName = ItemChoiceType.AmazonOrderID,
                    FulfillmentDate = DateTime.Now,
                    Item1 = orderItemList.ToArray(),
                    FulfillmentData = new OrderFulfillmentFulfillmentData() { Item = item.CarrierName, ShipperTrackingNumber = item.ShipperTrackingNumber, ShippingMethod = item.ShippingMethod }
                };
                orderList.Add(SysCommon.XmlHelper.ObjectToXmlSerializer(Model, false));
            }
            List<AmazonEnvelopeMessage> lsm = HelperController.AmazonEnvelopeMessageList<OrderFulfillment>(orderList);
            string str = SysCommon.XmlHelper.ObjectToXmlSerializer(HelperController.AmazonEnvelopeObject(appkey.MerchantCode, lsm, AmazonEnvelopeMessageType.OrderFulfillment));

            FeedsInfo info = new FeedsInfo()
            {
                AccountInfoId = appkey.AccountInfoID,
                SiteId = appkey.MarketplacesID ?? -1,
                AmazonEnvelope = str,
                CreateTime = DateTime.Now,
                IsDel = false,
                AdReleaseIdList = string.Join(",", list.Select(s => s.AmazonOrderFulfillmentID)),
                CreateUser = "CreateFulfillment",
                UpdateTime = DateTime.Now,
                UpdateUser = "Fulfillment",
                FeedType = FeedType._POST_ORDER_FULFILLMENT_DATA_.ToString(),
                FeedProcessingStatus = FeedProcessingStatus.Upload.ToString()
            };
            return info;
        }

        public static void OrderTrackingNumber(AppKey appkey)
        {
            OrderFulfillment model = new OrderFulfillment()
            {
                Item = "116-9620883-5612202",
                ItemElementName = ItemChoiceType.AmazonOrderID,
                FulfillmentDate = DateTime.Now,
                FulfillmentData = new OrderFulfillmentFulfillmentData()
                {
                    Item = "USPS",// CarrierCode.USPS,
                    ShippingMethod = "USPS",
                    ShipperTrackingNumber = "LS233613531CN"
                }
            };
            List<OrderFulfillmentItem> listItem = new List<OrderFulfillmentItem>();
            OrderFulfillmentItem item = new OrderFulfillmentItem()
            {
                Item = string.Format("{0}", "69623704208010"),
                ItemElementName = ItemChoiceType1.AmazonOrderItemCode,
                Quantity = "1"
            };
            listItem.Add(item);
            model.Item1 = listItem.ToArray();

            List<string> li = new List<string>();
            string xml = SysCommon.XmlHelper.ObjectToXmlSerializer(model, false);
            li.Add(xml);

            List<AmazonEnvelopeMessage> lsm = HelperController.AmazonEnvelopeMessageList<OrderFulfillment>(li);

            AmazonMODEL.AmazonEnvelope ep = HelperController.AmazonEnvelopeObject("A39MRJ0QCUL82E", lsm, AmazonEnvelopeMessageType.OrderFulfillment);


            try
            {
                string str = SysCommon.XmlHelper.ObjectToXmlSerializer(ep);
            }
            catch (Exception)
            {

            }

        }
    }
}
